//
//  SMDTableViewIndexView.m
//  Echo
//
//  Created by robu on 15/2/2.
//  Copyright (c) 2015年 Static Ga. All rights reserved.
//

#import "YXTableViewIndexView.h"
#import "WAWCollectionViewCell.h"


@interface YXTableViewIndexView()<UICollectionViewDelegate,UICollectionViewDataSource>


@property (assign,nonatomic) CGFloat titleLabelW;
@property (assign,nonatomic) CGFloat titleLabelH;
@property (assign,nonatomic) CGFloat titleLabelFont;
@property (assign,nonatomic) CGFloat titleLabelTopMargin;
@property (assign,nonatomic) CGFloat titleLabelRightMargin;
@property (assign,nonatomic) CGFloat titleLabelVerticalMargin;

@property (strong,nonatomic)NSMutableArray * titlesArray;
@property (strong,nonatomic)NSMutableArray * titleLabelsArray;
@property (strong,nonatomic)NSMutableArray * titleLabelCacheArray;

@property (assign,nonatomic)BOOL isMoveOutView;//touches事件是否移动超出当前view
@property (strong,nonatomic) UIImageView * titleTipImageView;
@property (strong,nonatomic) UILabel * titleTipLabel;
@property (strong,nonatomic) UILabel * currentLabel;

@property(nonatomic,assign) CGRect initFrame;

@property(nonatomic,assign) BOOL isLongGestEffied;

@end
@implementation YXTableViewIndexView


-(instancetype)initWithFrame:(CGRect)frame{
    if(self == [super initWithFrame:frame]){
        self.initFrame = frame;
        [self initData];
        [self initUI];
        
        
    }
    return self;
}


-(void) longGesAction:(UILongPressGestureRecognizer*)gest{
    self.isLongGestEffied = YES;
    NSLog(@"长按事件");
}

-(void)initData{
    if(nil == self.titleLabelsArray){
        self.titleLabelsArray = [[NSMutableArray alloc] init];
    }
    if(nil == self.titleLabelCacheArray){
        self.titleLabelCacheArray = [[NSMutableArray alloc] init];
    }
    
    self.titleLabelW = self.bounds.size.width;
    self.titleLabelTopMargin = 20 ;
    self.titleLabelVerticalMargin = 5;
    self.titleLabelH =  0;
    self.titleLabelFont = 12;
    
}
-(void)initUI{
    self.backgroundColor = [UIColor whiteColor];
    self.isShowTipView = NO;
    
    if(nil == self.titleTipImageView){
        self.titleTipImageView = [[UIImageView alloc] init];
    }
    if(nil == self.titleTipLabel){
        self.titleTipLabel = [[UILabel alloc] init];
    }
    
    self.titleTipImageView.frame = CGRectMake(-(10/2.0+110/2.0), 0, 110/2.0, 100/2.0);
    
    CGFloat ZYX_SCREEN_WIDTH = [[UIScreen mainScreen] bounds].size.width;
    CGFloat ZYX_SCREEN_HEIGHT = [[UIScreen mainScreen] bounds].size.height;
    
    CGFloat centerX = -ZYX_SCREEN_WIDTH/2.0+self.frame.size.width;
    CGFloat centerY = ZYX_SCREEN_HEIGHT/2.0-64;
    self.titleTipImageView.center = CGPointMake(centerX, centerY);
    
    self.titleTipImageView.backgroundColor = [UIColor colorWithRed:1/225.0 green:205/255.0 blue:206/255.0 alpha:1];
    self.titleTipImageView.layer.masksToBounds = YES;
    self.titleTipImageView.layer.cornerRadius = 4;
    
    self.titleTipLabel.frame = self.titleTipImageView.bounds;
    
    
    self.titleTipLabel.font = [UIFont systemFontOfSize:17];
    self.titleTipLabel.textAlignment = NSTextAlignmentCenter;
    self.titleTipLabel.textColor = [UIColor whiteColor];
    self.titleTipLabel.backgroundColor = [UIColor whiteColor];
    [self.titleTipImageView addSubview:self.titleTipLabel];
    
    self.titleTipImageView.hidden = YES;
    [self addSubview:self.titleTipImageView];
}

-(void)setTipViewBackgroundImage:(UIImage *)tipViewBackgroundImage{
    _tipViewBackgroundImage = tipViewBackgroundImage;
    self.titleTipImageView.image = _tipViewBackgroundImage;
}
-(void)setTipViewBackgroundColor:(UIColor *)tipViewBackgroundColor{
    _tipViewBackgroundColor = tipViewBackgroundColor;
    self.titleTipImageView.backgroundColor = _tipViewBackgroundColor;
}
-(void)setTipViewTitleColor:(UIColor *)tipViewTitleColor{
    _tipViewTitleColor = tipViewTitleColor;
    self.titleTipLabel.textColor = _tipViewTitleColor;
}
-(void)setTipViewTitleFont:(UIFont *)tipViewTitleFont{
    _tipViewTitleFont = tipViewTitleFont;
    self.titleTipLabel.font = _tipViewTitleFont;
}


-(void)setIndexTitlesArray:(NSArray*)titlesArray{
    if(nil == self.titlesArray){
        self.titlesArray = [[NSMutableArray alloc] init];
    }
    [self.titlesArray removeAllObjects];
    [self.titlesArray addObjectsFromArray:titlesArray];
    [self.titleLabelCacheArray addObjectsFromArray:self.titleLabelsArray];
    [self.titleLabelsArray removeAllObjects];
    
    [self refreshLeftUI];
    [self refreshRightUI];
}

//刷新左侧竖条
-(void)refreshLeftUI{
    
    if(self.titlesArray.count<=0){
        return;
    }
    for(UIView * view in self.subviews){
        if([view isKindOfClass:[UILabel class]] && view != self.titleTipLabel){
            [view removeFromSuperview];
        }
    }
    self.titleLabelW = 30;
    self.titleLabelH = (self.bounds.size.height - ((self.titlesArray.count-1) *self.titleLabelVerticalMargin) - self.titleLabelTopMargin * 2) / self.titlesArray.count;
    
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat w = self.titleLabelW;
    CGFloat h = self.titleLabelH;
    for(int i = 0;i<self.titlesArray.count;i++){
        
        NSString * title = self.titlesArray[i];
        UILabel * label = [self getCacheLabel];
        if(nil == label){
            label = [[UILabel alloc] init];
        }
        y = (h+self.titleLabelVerticalMargin) * i +self.titleLabelTopMargin;
        
        label.frame = CGRectMake(x, y, w, h);
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:self.self.titleLabelFont];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor clearColor];
        label.tag = i + 100;
        
        label.text = title;
        [self addSubview:label];
        [self.titleLabelsArray addObject:label];
    }
    CGPoint tCenter = self.titleTipImageView.center;
    tCenter.y = self.frame.size.height/2.0;
    self.titleTipImageView.center = tCenter;
}


-(void)refreshRightUI{
    
    
    CGFloat w = (self.bounds.size.width - self.titleLabelW) / 3;
    CGFloat h = self.bounds.size.height / 9;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);//设置内容的内边距
    flowLayout.minimumInteritemSpacing = 0;//设置每个cell之间的最小间距
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;//设置滚动方向
    flowLayout.itemSize = CGSizeMake(w, h);
    
    CGRect frame =  CGRectMake(self.titleLabelW, 0, self.bounds.size.width - self.titleLabelW, self.bounds.size.height);
    
    UICollectionView * colloectView = [[UICollectionView alloc]initWithFrame:frame collectionViewLayout:flowLayout];
    colloectView.dataSource = self;
    colloectView.delegate = self;
    colloectView.backgroundColor = [UIColor whiteColor];
    
    [colloectView registerClass:[WAWCollectionViewCell class] forCellWithReuseIdentifier:@"CellID"];
    
    [self addSubview:colloectView];
    [colloectView reloadData];
    
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.titlesArray.count ;

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * CellID = @"CellID";
    
    WAWCollectionViewCell * cell = (WAWCollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:CellID forIndexPath:indexPath];
    cell.wlabel.text = self.titlesArray[indexPath.row];
    cell.layer.borderWidth = 1;
    cell.layer.borderColor = [UIColor darkGrayColor].CGColor;
    cell.layer.masksToBounds = YES;
    NSInteger row = (indexPath.item % 6) / 3;
    cell.backgroundColor = row ?[UIColor whiteColor]:[UIColor lightGrayColor];

    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row < self.titlesArray.count - 1) {
     
        NSString * title = self.titlesArray[indexPath.item];
        
        if ([self.tabelViewIndexViewDelegate respondsToSelector:@selector(tableViewSectionIndexTitle:atIndex:)]) {
            [self.tabelViewIndexViewDelegate tableViewSectionIndexTitle:title atIndex:indexPath.item];
        }
    }
    CGRect rect =  CGRectMake(self.superview.bounds.size.width - 30, self.frame.origin.y, self.bounds.size.width, self.tableView.bounds.size.height);
    [UIView animateWithDuration:0.25 animations:^{
        self.frame = rect;
    }];
}


/* 事件处理 */
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    self.isMoveOutView = NO;
    self.currentLabel = nil;
    self.backgroundColor = [UIColor lightGrayColor];
    UITouch *touch=[touches anyObject];
    CGPoint location = [touch locationInView:self];
    [self indexTouchedInView:location];
    
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    
    self.backgroundColor = [UIColor whiteColor];
    UITouch *touch=[touches anyObject];
    CGPoint location = [touch locationInView:self];
    if(!self.isMoveOutView){//点击事件有效
        [self indexTouchedInView:location];
    }else{//点击事件无效
    
    }
    NSLog(@"点击结束");
    self.titleTipImageView.hidden = YES;
    self.currentLabel.backgroundColor = [UIColor clearColor];
    self.currentLabel = nil;
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    
    UITouch *touch=[touches anyObject];
    CGPoint location = [touch locationInView:self];
    CGPoint preLocation = [touch previousLocationInView:self];
    
    CGFloat offsetX = location.x - preLocation.x;
    CGSize sSize = [UIScreen mainScreen].bounds.size;
    CGSize selfSize = self.bounds.size;
    
    NSLog(@"Move ---- %lf,%lf",location.x,location.y);
    
    if (![self pointInside:[touch locationInView:self] withEvent:nil]) {
        self.isMoveOutView = YES;
    }else{
        self.isMoveOutView = NO;
        UIView *hitView=[self hitTest:[[touches anyObject] locationInView:self] withEvent:nil];
        if (hitView==self){
            NSLog(@"touches moved in the view");
            if (offsetX < 0) {
                if ((self.frame.origin.x + offsetX) < (sSize.width - selfSize.width)) {
                    self.frame = CGRectMake(sSize.width - selfSize.width, self.frame.origin.y, selfSize.width, selfSize.height);
                    self.backgroundColor = [UIColor lightGrayColor];
                    return;
                }
                NSLog(@"\n%f ----- %f",self.frame.origin.x,self.initFrame.origin.x);
                if (self.frame.origin.x < self.initFrame.origin.x - 100) {
                    self.frame = CGRectMake(self.superview.frame.size.width - self.initFrame.size.width, self.frame.origin.y, self.initFrame.size.width, self.initFrame.size.height);
                }else{
                    if (self.isLongGestEffied) {
                        self.transform = CGAffineTransformTranslate(self.transform, offsetX, 0);
                    }
                }
                return;
            }if (offsetX > 0) {
               
            }
        }else{
            NSLog(@"touches moved in the subview");
        }
        [self indexTouchedInView:location];
    }
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
    self.backgroundColor = [UIColor whiteColor];
    self.titleTipImageView.hidden = YES;
    
    self.currentLabel.backgroundColor = [UIColor clearColor];
    self.currentLabel = nil;
    
}
-(NSInteger)indexTouchedInView:(CGPoint)location{
    
    if (location.x > self.titleLabelW) {
        return -1;
    }
    
    NSInteger index = [self getCurrentLabelWithLoactionY:location.y];
    
    if(index<0){
        return index;
    }
    
    NSString * title = self.titlesArray[index];
    self.titleTipLabel.text = title;
    
    UILabel * label = [self viewWithTag:index + 100];
    
    self.currentLabel.backgroundColor = [UIColor clearColor];
    self.currentLabel = label;
    self.currentLabel.backgroundColor = [UIColor redColor];
    
    if(self.isShowTipView){
        self.titleTipImageView.hidden = NO;
        self.titleTipLabel.hidden = NO;
    }else{
        self.titleTipImageView.hidden = YES;
        self.titleTipLabel.hidden = YES;
    }
    if([self.tabelViewIndexViewDelegate respondsToSelector:@selector(tableViewSectionIndexTitle:atIndex:)]){
        [self.tabelViewIndexViewDelegate tableViewSectionIndexTitle:title atIndex:index];
    }
    return index;
}


#pragma mark 从缓存池取label
-(UILabel*)getCacheLabel{
    UILabel * label = nil;
    if(self.titleLabelCacheArray.count > 0){
        label = [self.titleLabelCacheArray lastObject];
        [self.titleLabelCacheArray removeLastObject];
    }
    return label;
}

//根据点击的Y值获取当前的Label的Index
-(NSInteger)getCurrentLabelWithLoactionY:(CGFloat)locationY{
    
    NSInteger index = (locationY - self.titleLabelTopMargin) / (self.titleLabelH+self.titleLabelVerticalMargin);
    
    if(index>=self.titlesArray.count){
        index = self.titlesArray.count - 1;
    }
    if(index<0){
        index = 0;
    }
    if(0 == self.titlesArray.count){
        return -1;
    }
    return index;
}





@end
